package net.cmkj.mine.interceptor;

import java.io.PrintWriter;
import java.io.StringWriter;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;

import net.cmkj.mine.bean.SysLog;
import net.cmkj.mine.bean.SysUser;
import net.cmkj.mine.util.CommonUtils;
import net.cmkj.mine.util.IWebUtils;

/**
 * 日志拦截器
 * @author zzcmkj
 *
 */
public class SysLogInterceptor implements Interceptor {

	public void intercept(Invocation inv) {
		String from = inv.getController().getRequest().getHeader("Referer");
		String ip = CommonUtils.getIP(inv.getController().getRequest());
		String className = inv.getController().getClass().getName();
		String methodName = inv.getMethodName();
		String params = inv.getController().getRequest().getQueryString();
		Integer uid = null;
		SysUser sysUser = IWebUtils.getCurrentSysUser(inv.getController().getRequest());
		if (sysUser != null) {
			uid = sysUser.getId().intValue();
		}
		long startTime = System.currentTimeMillis();
		try{
			inv.invoke();
			SysLog.dao.saveSysLog(uid, ip, from, inv.getActionKey(), className, methodName, startTime, 0, "", params);
		}catch(RuntimeException e){
			SysLog.dao.saveSysLog(uid, ip, from, inv.getActionKey(), className, methodName, startTime, -1, getExceptionAllinformation(e), params);
		}
	}

	/**
	 * 获取异常详细信息
	 */
	private static String getExceptionAllinformation(Throwable e) {
		StringWriter sw = new StringWriter();
		PrintWriter pw = new PrintWriter(sw, true);
		e.printStackTrace(pw);
		pw.flush();
		sw.flush();
		return sw.toString();
	}

}
